
import cv2
import pyzbar.pyzbar as pyzbar
import webbrowser
import os
from pygame import mixer
import time

def decodeDisplay(video,flag):
    # 转为灰度图像
    # gray = cv2.cvtColor(video, cv2.COLOR_BGR2GRAY)
    gray = video
    #选择图中的第一个二维码
    if len(pyzbar.decode(gray))!=0:
        barcode = pyzbar.decode(gray)[0]
        # 提取二维码的位置,然后用边框标识出来在视频中
        (x, y, w, h) = barcode.rect
        cv2.rectangle(video, (x, y), (x + w, y + h), (0, 255, 0), 2)
        # 字符串转换
        barcodeData = barcode.data.decode("utf-8")
        barcodeType = barcode.type
        # 在图像上面显示识别出来的内容
        # text = "{}".format(barcodeData)
        # cv2.putText(video, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX,1, (0, 255, 0), 2)
        # 打印识别后的内容
        # print("[扫描结果]: {0}".format(barcodeData))
        #识别到结果后打开网页，并将识别程序自动关闭(否则会不停的识别，弹出非常多的网页)
        # for i in range(0,1):
        #     result = barcodeData
        #     webbrowser.open(result)
        #     flag=27
        #     time.sleep(5)
        #     return flag
    cv2.imshow("QRCODE",video)

def detect():
    cap = cv2.VideoCapture(0)
    while(True):
        # 逐帧捕获
        ret, frame = cap.read()
        flag = cv2.waitKey(1)
        flag = decodeDisplay(frame,flag)
        if flag == 27:#按下ESC键退出
            break
    # 一切完成后，释放捕获
    cap.release()
    cv2.destroyAllWindows()

if __name__ == '__main__':
    detect()

